package com.xuanyuan.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xuanyuan.domain.AjaxResult;
import com.xuanyuan.entity.Dept;
import com.xuanyuan.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

@Validated
@Controller
@RequestMapping("/api/dept")
public class DeptController {
    @Autowired
    private DeptService deptService;

    @ResponseBody
    @RequestMapping("/page")
    public AjaxResult selectDeptPage(Dept dept, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return AjaxResult.success(new PageInfo<>(deptService.selectDeptList(dept)));
    }

    @ResponseBody
    @RequestMapping("/list")
    public AjaxResult selectDeptList(Dept dept) {
        return AjaxResult.success(deptService.selectDeptList(dept));
    }

    @ResponseBody
    @PostMapping("/add")
    public AjaxResult insertDept(@Validated Dept dept) {
        if (deptService.selectDeptByName(dept.getDeptName()) != null) {
            return AjaxResult.error("添加失败，该部门已存在，请换个名字！");
        } else {
            return AjaxResult.toAjax(deptService.insertDept(dept));
        }
    }

    @ResponseBody
    @PostMapping("/edit")
    public AjaxResult updateDept(@Validated Dept dept, @NotNull(message = "部门id不能为空") Integer id) {
        //必须需要id
        dept.setId(id);
        return AjaxResult.toAjax(deptService.updateDept(dept));
    }

    @ResponseBody
    @PostMapping("/removes")
    public AjaxResult deleteDeptByIds(@NotEmpty(message = "部门ids不能为空") String[] ids) {
        if (ids.length <= 0) {
            return AjaxResult.error("删除失败，未上传ids");
        }
        return AjaxResult.toAjax(deptService.deleteDeptByIds(ids));
    }
}

